'use client'

import { useEffect, useRef, useCallback } from 'react'

declare global {
  interface Window {
    AMap: any
  }
}

interface AMapProps {
  center?: [number, number] // 初始中心坐标 [lng, lat]
  zoom?: number // 初始缩放级别
  markers?: Array<{ position: [number, number]; title: string; icon: string; id: string; content: string }> // 标记点数组
}

export default function AMap({ center = [116.3975, 39.9085], zoom = 15, markers }: AMapProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const mapRef = useRef<AMap.Map | null>(null)

  const loadAMap = () => {
    window._AMapSecurityConfig = {
      securityJsCode: process.env.NEXT_PUBLIC_AMAP_SECURITY_CODE,
    }

    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${process.env.NEXT_PUBLIC_AMAP_KEY}`
    script.async = true
    script.onload = () => {
      if (containerRef.current) {
        mapRef.current = new window.AMap.Map(containerRef.current, {
          zoom: 15,
          // center,
          center: [116.397428, 39.90923],
          mapStyle: process.env.NEXT_PUBLIC_AMAP_AMAP_STYLE,
        })

        const initialPoints = [
          {
            id: '1',
            position: [116.397428, 39.90923],
            title: '天安门',

            icon: '/map-icons/icon_camera_inline.svg',
          },
          {
            id: '2',
            position: [116.407396, 39.904199],
            icon: '/map-icons/icon_camera_inline.svg',
          },
          {
            id: '3',
            position: [116.271729, 39.992894],
            icon: '/map-icons/icon_camera_inline.svg',
          },
        ]

        // 创建信息窗口内容
        //         const infoContent = `
        //         <div style="padding: 5px;color:blue;display:flex;opacity: 0.3;
        // background: rgba(0,0,0,0.80);
        // border: 0.8px solid rgba(255,255,255,1);
        // box-shadow: inset 0px 0px 4px 0px rgba(249,249,249,1);box-shadow: 0px 8px 8px 0px rgba(0,0,0,0.5);
        // border-radius: 10px;">
        //         <image src="/map-icons/icon_event.svg"/>
        //           <p>交通事故</p>
        //         </div>
        //       `

        const infoContent = index => {
          return `
        <div style="display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;" >
          <div class="close-btn" style="display:flex;" > 
          <image src="/map-icons/icon_event.svg"/>
          <span style="white-space: nowrap; ">交通事故</span>
          </div>
   
       <image   src="/map-icons/icon_camera_inline.svg"/>
        </div>
      `
        }

        initialPoints?.length &&
          initialPoints.forEach((markerData: any, index) => {
            const marker = new window.AMap.Marker({
              position: markerData.position,
              // icon: markerData.icon,
              content: infoContent(index), // 信息窗口内容

              map: mapRef.current,
            })

            console.log(markerData.position, '==坐标')

            // 绑定 Marker 点击事件
            // marker.on('click', e => {
            //   console.log(e, '==点击事件')

            //   // handleMarkerClick(markerData)
            // })

            mapRef.current.querySelector('.close-btn-0')?.addEventListener('click', event => {
              // event.stopPropagation()
              console.log('000', '==点击事件')
            })
          })
      }
    }

    document.head.appendChild(script)
  }

  // 初始化地图
  useEffect(() => {
    loadAMap()

    return () => {
      // 创建中止控制器
      const controller = new AbortController()
      controller.abort()

      // 销毁地图实例
      if (mapRef.current) {
        mapRef.current.destroy()
        mapRef.current = null
      }
    }
  }, [markers])

  // 添加/删除 Marker
  // useEffect(() => {
  //   console.log('渲染marker', !containerRef.current || !mapRef.current)
  //   console.log('渲染marker', markers)
  //   if (!containerRef.current || !mapRef.current) return

  //   // 清除所有现有 Marker
  //   mapRef.current.clearMap()

  //   markers?.length &&
  //     markers.forEach((markerData: any) => {
  //       const marker = new window.AMap.Marker({
  //         position: markerData.position,
  //         icon: markerData.icon,
  //         // content: markerData.content,
  //         // content: `<div style="padding:10px">
  //         // <svg src="markerData.icon style="width:50px;height:50px;border-radius:5px"></svg>
  //         // <div style="margin-top:5px">${'测试'}</div>
  //         // </div>`,
  //         map: mapRef.current,
  //       })

  //       // 绑定 Marker 点击事件
  //       marker.on('click', () => handleMarkerClick(markerData))
  //     })
  // }, [markers])

  // 处理 Marker 点击（删除）
  const handleMarkerClick = (markData: number) => {
    console.log('==点击marker', markData)

    // setMarkers(prev => prev.filter(marker => marker.id !== id))
  }
  return (
    <div
      ref={containerRef}
      style={{ width: '100%', height: '100%' }}
    />
  )
}
